package com.life.notes.config.security.handler;

import com.life.notes.config.security.JWTConfig;
import com.life.notes.config.security.model.SysUserDetails;
import com.life.notes.config.utils.JWTTokenUtil;
import com.life.notes.config.utils.ResponseMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理类
 * @author lishuqian
 * @date 2020/6/16
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    /**
     * 登录成功返回结果
     * @author zwq
     * @date 2020/4/4
     * @param request
     * @param response
     * @param authentication
     * @return
     **/
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 组装JWT
        SysUserDetails sysUserDetails =  (SysUserDetails) authentication.getPrincipal();
        String token = JWTTokenUtil.createAccessToken(sysUserDetails);
        token = JWTConfig.tokenPrefix + token;
        ResponseMsgUtil.responseJson(response,ResponseMsgUtil.success(token));
    }
}
